<template>
  <div class="divBackground">
    <div class="loginDiv">
      <el-form ref="form" :model="loginForm" style="width: 100%; margin: 0 auto;">
        <el-form-item prop="username">
          <el-input v-model="loginForm.username" placeholder="请输入账号"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="loginForm.password" placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="login()" style="width: 100%">登录</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import apiClient from '@/utils/axios'
import { ElMessage } from 'element-plus'

interface LoginForm {
  username: string
  password: string
}

const router = useRouter()

const loginForm = reactive<LoginForm>({
  username: '',
  password: '',
})

const login = () => {
  if (loginForm.username === '' || loginForm.password === '') {
    ElMessage({
      message: '账号或密码不能为空',
      type: 'warning',
      placement: 'top-right',
    })
    return
  }
  apiClient
    .post('/admin/login', {
      username: loginForm.username,
      password: loginForm.password,
    })
    .then((result) => {
      if (result.data.status === 200) {
        sessionStorage.setItem('a', loginForm.username)
        ElMessage({
          message: result.data.msg,
          type: 'success',
          placement: 'top-right',
        })
        localStorage.setItem('a', loginForm.username)
        localStorage.setItem('b', loginForm.password)
        router.push({ name: 'AdminUser' })
      } else {
        ElMessage({
          message: result.data.msg,
          type: 'error',
          placement: 'top-right',
        })
      }
    })
}

onMounted(() => {
  loginForm.username = localStorage.getItem('a') || ''
  loginForm.password = localStorage.getItem('b') || ''
  if (loginForm.username !== '' && loginForm.password !== '') {
    login()
  }
})
</script>

<style scoped>
.divBackground {
  height: 95vh;
  border: 1px solid #545454;
  border-radius: 5px;
  margin: 5px;
  background-color: #e5d3ca;
}

.loginDiv {
  text-align: center;
  width: 50%;
  padding: 50px;
  border: 1px solid #483939;
  background-color: #ffffff;
  box-shadow: rgba(0, 0, 0, 0.3) 0px 19px 38px, rgba(0, 0, 0, 0.22) 0px 15px 12px;
  border-radius: 10px;
  margin: 30vh auto 0;
}

</style>